<template>
    <div class="sign-in-container">
        <PageHeader title="每日打卡" />
        <div class="form-section">
            <div class="form-header">
                <div class="location-type-selector">
                    <label class="radio-label">
                        <input 
                            type="radio" 
                            v-model="locationType" 
                            value="map"
                            name="location-type"
                        >
                        使用地图位置
                    </label>
                    <label class="radio-label">
                        <input 
                            type="radio" 
                            v-model="locationType" 
                            value="custom"
                            name="location-type"
                        >
                        自定义地址
                    </label>
                </div>
            </div>

            <div class="location-content">
                <MapLocation 
                    v-if="locationType === 'map'"
                    ref="mapLocationRef"
                    @update:location="handleLocationSelected"
                />
                <MyLocation 
                    v-else
                    ref="myLocationRef"
                    @update:address="handleCustomAddressUpdate"
                />
            </div>

            <div class="form-group">
                <label class="form-label">备注信息</label>
                <textarea 
                    v-model="remarks"
                    placeholder="请输入备注信息（选填）"
                    class="remarks-input"
                ></textarea>
            </div>
            <div class="form-group upload-group">   
                <ImageUpload 
                    v-model="images"
                    label="上传图片"
                    placeholder="点击上传图片"
                    :multiple="true"
                    :upload-type="'zhjy'"
                    :maxCount="1"
                    :maxSize="5 * 1024 * 1024"
                    @error="handleError"
                />
            </div>
            <!-- <div class="form-group upload-group">   
                <UpLoadFile 
                    v-model="files"
                    label="上传文件"
                    :upload-type="'zhjy'"
                    placeholder="点击上传文件"
                    :multiple="true"
                    :maxCount="2"
                    :maxSize="10 * 1024 * 1024"
                    @error="handleError"
                />
            </div> -->

            <button 
                @click="submitCheckIn" 
                class="submit-btn"
                :disabled="!canSubmit || isSubmitting"
            >
                {{ isSubmitting ? '提交中...' : '提交打卡' }}
            </button>
        </div>

        <div class="records-section">
            <div class="records-header">
                <h3>打卡记录数量 {{ logTotal }}</h3>
                <lay-form-item label="" mode="inline">
                    <lay-date-picker @change="changeSelectTime" v-model="logTime_selector" placeholder="选择查询的日期" allow-clear></lay-date-picker>
                </lay-form-item>
            </div>
            <div class="records-list">
                <div v-if="loading" class="loading-container">
                    <van-loading type="spinner" color="#1E9FFF" />
                    <span>加载中...</span>
                </div>
                <div v-else-if="logRows.length === 0" class="no-data">
                    暂无打卡记录
                </div>
                <TransitionGroup name="list" tag="div" v-else>
                    <div v-for="(log, index) in logRows" :key="index" class="record-item">
                        <div class="record-header">
                            <div class="record-time">{{ log.clockTime }}</div>
                            <div class="record-status">已打卡</div>
                        </div>
                        <div class="record-content">
                            <div class="record-address">
                                <van-icon name="location-o" />
                                <span>{{ log.clockAddress }}</span>
                            </div>
                            <div v-if="log.clockContent" class="record-remarks">
                                <van-icon name="comment-o" />
                                <span>{{ log.clockContent }}</span>
                            </div>
                            <div v-if="log.filePath" class="record-images">
                                <div class="images-grid">
                                    <div 
                                        v-for="(imageUrl, imgIndex) in log.filePath.split(',')" 
                                        :key="imgIndex"
                                        class="image-item"
                                    >
                                        <div class="image-container">
                                            <img :src="imageUrl" :alt="'打卡图片' + (imgIndex + 1)">
                                        </div>
                                        <button class="preview-btn" @click.stop="previewImage(log.filePath.split(','), imgIndex)">
                                            <van-icon name="search" size="16" />
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </TransitionGroup>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { Icon as VanIcon } from 'vant';
import MapLocation from './mapLocation/index.vue';
import MyLocation from './myLocation/index.vue';
import { router } from '@inertiajs/vue3';
import RouterPath from '@/constans/RouterPath.js'
import { usePage } from '@inertiajs/vue3';
import apiUrls from '@/config/apiUrls'; 
import request from '@/utils/request';
import {getTimeY_d_m} from '@/utils/utils'
import ImageUpload from '@/Pages/compontents/ImageUpload.vue';
import { showToast, showImagePreview } from 'vant';
import UpLoadFile from '@/Pages/compontents/UpLoadFile.vue';
import PageHeader from '@/Pages/compontents/PageHeader.vue';
const logRows = ref([]);
const logTotal = ref(0);
const logTime_selector = ref(getTimeY_d_m());
const loading = ref(false);

const getZhjyClocks = async (time) => {
    try {
        loading.value = true;
        const response = await request.get(apiUrls.zhjy.getZhjyClocks, {
            params: { queryDate: time }
        });
        const code = response['code']
        if (code === 200) {
            const rows = response['rows']
            const total = response['total']
            logRows.value = rows;
            logTotal.value = total;
        } else {
            console.log('打卡列表获取失败');
            showToast('获取打卡记录失败');
        }
    } catch (error) {
        console.error('获取打卡记录失败:', error);
        showToast('获取打卡记录失败，请重试');
    } finally {
        loading.value = false;
    }
}

const changeSelectTime = async (time) => {
    getZhjyClocks(time);
}

onMounted(() => {
    changeSelectTime(logTime_selector.value)
});

const locationType = ref('map');
const selectedLocation = ref(null);
const customAddress = ref('');
const remarks = ref('');
const images = ref([]);
const files = ref([]);

const mapLocationRef = ref(null);
const myLocationRef = ref(null);

const handleLocationSelected = (location) => {
    selectedLocation.value = location;
};

const handleCustomAddressUpdate = (address) => {
    customAddress.value = address;
};

// 监听位置类型变化
watch(locationType, (newType) => {
    // 重置位置信息
    if (newType === 'map') {
        customAddress.value = '';
        if (myLocationRef.value) {
            myLocationRef.value.customAddress = '';
            myLocationRef.value.selectedCity = '';
        }
    } else {
        selectedLocation.value = null;
    }
});

const canSubmit = computed(() => {
    const hasLocation = locationType.value === 'map' 
        ? selectedLocation.value !== null
        : customAddress.value.trim() !== '';
    
    const hasImages = images.value && images.value.length > 0;
    
    return hasLocation && hasImages;
});

const isSubmitting = ref(false);

const submitCheckIn = async () => {
    if (isSubmitting.value) return;
    
    try {
        isSubmitting.value = true;
        // 检查是否有图片
        if (!images.value || images.value.length === 0) {
            showToast('请上传图片');
            return;
        }

        // 检查位置信息
        if (!selectedLocation.value && !customAddress.value) {
            showToast('请选择位置');
            return;
        }

        // 构建提交数据
        const submitData = {
            clockAddress: locationType.value === 'map' 
                ? selectedLocation.value.address 
                : customAddress.value,
            clockContent: remarks.value,
            filePath: images.value.map(img => img.url).join(','), // 将图片URL数组转换为逗号分隔的字符串
            fileIds: images.value.map(img => img.id).join(','), // 将图片ID数组转换为逗号分隔的字符串
            orgUrls: images.value.map(img => img.orgUrl).join(','), // 将图片相对路径数组转换为逗号分隔的字符串
        };
        console.log(submitData);
        

        // 发送请求
        const response = await request.post(apiUrls.zhjy.saveZhjyClock, submitData);
        console.log(response);
        
        if (response.code === 200) {
            showToast('打卡成功');
            // 重置表单
            resetForm();
            // 刷新打卡记录
            changeSelectTime(logTime_selector.value);
        } else {
            showToast(response.message || '打卡失败');
        }
    } catch (error) {
        console.error('打卡失败:', error);
        showToast('打卡失败，请重试');
    } finally {
        isSubmitting.value = false;
    }
};

const resetForm = () => {
    if (locationType.value === 'map') {
        selectedLocation.value = null;
    } else {
        customAddress.value = '';
        if (myLocationRef.value) {
            myLocationRef.value.customAddress = '';
            myLocationRef.value.selectedCity = '';
        }
    }
    remarks.value = '';
    images.value = [];
};

const handleError = (error) => {
    console.error('上传错误:', error);
    showToast('上传失败，请重试');
};

const handleBack = () => {
    router.visit(RouterPath.users.home); 
};

const previewImage = (images, startPosition) => {
    showImagePreview({
        images,
        startPosition,
        closeable: true,
        closeIconPosition: 'top-right',
    });
};
</script>

<style scoped>
.sign-in-container {
    display: flex;
    flex-direction: column;
    gap: 20px;
    padding: 20px;
    max-width: 800px;
    margin: 0 auto;
}

.page-header {
    background: white;
    padding: 12px 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    margin-bottom: 20px;
}

.header-content {
    display: flex;
    align-items: center;
    gap: 12px;
    max-width: 800px;
    margin: 0 auto;
}

.back-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 36px;
    height: 36px;
    background: #f5f5f5;
    border: none;
    border-radius: 50%;
    color: #333;
    cursor: pointer;
    transition: all 0.3s;
}

.back-btn:hover {
    background: #e8e8e8;
    transform: scale(1.05);
}

.header-content h2 {
    margin: 0;
    font-size: 18px;
    color: #333;
    font-weight: 500;
}

.form-section {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.form-header {
    margin-bottom: 20px;
}

.form-header h2 {
    margin: 0 0 15px;
    font-size: 18px;
    color: #333;
}

.location-type-selector {
    display: flex;
    gap: 20px;
}

.radio-label {
    display: flex;
    align-items: center;
    gap: 6px;
    cursor: pointer;
    color: #666;
    font-size: 14px;
}

.radio-label input[type="radio"] {
    margin: 0;
}

.location-content {
    margin-bottom: 20px;
}

.form-group {
    margin-bottom: 20px;
}

.upload-group {
    margin-top: 24px;
    margin-bottom: 24px;
}

.form-label {
    display: block;
    margin-bottom: 8px;
    color: #333;
    font-size: 14px;
}

.remarks-input {
    width: 100%;
    min-height: 80px;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 6px;
    resize: vertical;
    font-size: 14px;
    transition: border-color 0.3s;
}

.remarks-input:focus {
    border-color: #1E9FFF;
    outline: none;
}

.submit-btn {
    width: 100%;
    padding: 12px;
    background: #1E9FFF;
    color: white;
    border: none;
    border-radius: 6px;
    font-size: 16px;
    cursor: pointer;
    transition: background-color 0.3s;
}

.submit-btn:hover:not(:disabled) {
    background: #1890ff;
}

.submit-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
}

.records-section {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.records-section h3 {
    margin: 0 0 15px;
    font-size: 16px;
    color: #333;
}

.records-list {
    position: relative;
    min-height: 200px;
}

.record-item {
    padding: 12px;
    border-bottom: 1px solid #eee;
    margin-bottom: 10px;
    transition: all 0.3s ease;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.record-item:last-child {
    border-bottom: none;
    margin-bottom: 0;
}

.record-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.record-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
}

.record-time {
    font-size: 12px;
    color: #999;
}

.record-status {
    font-size: 12px;
    color: #52c41a;
    background-color: rgba(82, 196, 26, 0.1);
    padding: 2px 8px;
    border-radius: 10px;
}

.record-content {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.record-address {
    display: flex;
    align-items: flex-start;
    gap: 6px;
    color: #333;
    font-size: 14px;
}

.record-remarks {
    display: flex;
    align-items: flex-start;
    gap: 6px;
    color: #666;
    font-size: 14px;
}

.record-images {
    margin-top: 12px;
}

.images-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
}

.image-item {
    position: relative;
    aspect-ratio: 1;
    border-radius: 4px;
    overflow: hidden;
    border: 1px solid #eee;
    cursor: pointer;
    background-color: #f8f9fa;
}

.image-container {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    padding: 4px;
}

.image-item img {
    width: 100%;
    height: 100%;
    object-fit: contain;
    transition: transform 0.3s;
}

.image-item:hover img {
    transform: scale(1.05);
}

.preview-btn {
    position: absolute;
    top: 4px;
    left: 4px;
    background: rgba(255, 255, 255, 0.9);
    color: #1E9FFF;
    border: none;
    border-radius: 50%;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 12px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    z-index: 2;
}

.preview-btn:hover {
    background: #1E9FFF;
    color: white;
    transform: scale(1.1);
}

/* 自定义滚动条样式 */
.records-list::-webkit-scrollbar {
    width: 6px;
}

.records-list::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.records-list::-webkit-scrollbar-thumb {
    background: #ccc;
    border-radius: 3px;
}

.records-list::-webkit-scrollbar-thumb:hover {
    background: #999;
}

.loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 0;
    gap: 12px;
}

.loading-container span {
    color: #666;
    font-size: 14px;
}

/* 列表过渡动画 */
.list-enter-active,
.list-leave-active {
    transition: all 0.5s ease;
}

.list-enter-from {
    opacity: 0;
    transform: translateY(30px);
}

.list-leave-to {
    opacity: 0;
    transform: translateY(-30px);
}

/* 确保离开的元素不会影响布局 */
.list-leave-active {
    position: absolute;
}

/* 优化无数据状态的样式 */
.no-data {
    text-align: center;
    padding: 40px 0;
    color: #999;
    font-size: 14px;
}
</style>    